<?php
/** @noinspection SpellCheckingInspection */
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Util.php';

use Dotenv\Dotenv;
$notFound = <<<HTML
<p style="height: 90%;display: flex;align-items: center;justify-content: center"><span style="font-size: 2rem;padding-right: 1rem;">404</span> | <span style="padding-left: 1rem;font-weight: normal;font-size: 1.5rem">Not Found</span></p>
HTML;
// 定义基本路径
const BASE_PATH = __DIR__;
$dotenv = Dotenv::createImmutable(__DIR__); // 指定.env文件所在的目录
$dotenv->load(); // 加载.env文件
// $ipWhitelist = [
//     '113.250.223.68',
//     '127.0.0.1'
// ];
// $ip = Util::getip();
// if (!in_array($ip, $ipWhitelist)) {
//     die('<style>*{margin: 0;padding: 0;}</style><h2 style="text-align: center;display: flex;height: 100%;align-items: center;justify-content: center;">403 | 禁止访问</h2>' . PHP_EOL);
// }
$key = $_ENV['KEY'];
session_start();
$user = $_SESSION['u']??null;
$pathId = $_SESSION['path_id']??null;

$websites = file_get_contents(__DIR__ . '/data.json');

if (!empty($websites) && json_decode($websites)) {
    $websites = json_decode($websites, true);
} else {
    $websites = [];
}
$templateData = [
    'user' => $user,
    'key' => $key,
    'websites' => $websites,
    'path_id' => $pathId
];

function msg($code = 1, $msg = '成功', $data = "")
{
    $json = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
    header('Content-Type:application/json');
    echo json_encode($json, JSON_PRETTY_PRINT);
    exit;
}


function skipFiles(): array
{
    return [
        '.user.ini',
        '.htaccess',
        '.env',
        '.',
        '..',
        'miss.json',
        'app-ads.txt',
        'iframe.html',
    ];
}


// 自动加载类
spl_autoload_register(function ($class) {
    $classPath = str_replace('\\', '/', $class) . '.php';
    $fullPath = BASE_PATH . '/' . $classPath;
    global $notFound;
    if (!file_exists($fullPath)) {
        http_response_code(404);
        echo $notFound;
        exit;
    }
    include_once $fullPath;
});

// 解析请求
$request = $_SERVER['REQUEST_URI'];
$requestParts = explode('/', trim($request, '/'));
$controllerName = !empty($requestParts[0]) ? ucfirst($requestParts[0]) . 'controller' : 'Index';
$action = !empty($requestParts[1]) ? $requestParts[1] : 'index';

// 实例化控制器并调用动作方法
$controllerClassName = 'controller\\' . $controllerName;
if (class_exists($controllerClassName)) {
    $controller = new $controllerClassName();
    if (method_exists($controller, $action)) {
        $controller->$action();
        exit;
    }
}
http_response_code(404);
echo $notFound;
exit;